import re
import logging
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
import json
# Create your views here.
from django.views import View
from apps.checkmail.utils import check_email_token, generate_email
from celery_tasks.email.tasks import send_verify_email

from utils.response_code import RETCODE

loger = logging.getLogger('django')


class EmailView(LoginRequiredMixin, View):
    # 短信发送
    def put(self, request):
        # 接受参数
        dict = json.loads(request.body.decode())
        email = dict.get('email')
        # 校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseBadRequest('参数email有误')
        # 保存数据
        try:
            request.user.email = email
            request.user.save()
        except Exception:
            return http.JsonResponse({'code': RETCODE.EMAILERR, 'errmsg': '信箱错误'})
        # 发送并加密数据
        verify_url = generate_email(request.user)
        send_verify_email.delay(email, verify_url)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


class CheckEmailView(View):
    def get(self, request):
        token = request.GET.get('token')

        if token is None:
            return http.HttpResponseBadRequest('发生错误')

        user = check_email_token(token)
        if not user:
            return http.HttpResponseBadRequest('无效的token')

        try:
            user.email_active = True
            user.save()
        except:
            return http.HttpResponseBadRequest('无效的token')

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
